package com.mediacloud.app.newsmodule.view;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;

import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.eventTrack.TXReportManager;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.views.ImageButtonX;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.ComponentClickUtils;

import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.reslib.util.AppFontToolKt;

public class HorseNightView extends RelativeLayout {
  //  protected LinearLayout mHorseNightContainer;
    protected int mContainerMesureWidh = 0;
    protected int mContainerMesurHeight = 0;
    protected int mContainerLookWidth = 0;
   // protected HorseNightScroller mHorseNightScroller;
//    protected ScrollHandle mHandler = new ScrollHandle();
    protected ImageButtonX mTop_back;
    protected ImageView ass_top_titel_image;
    protected TextView ass_top_titel;
    protected ImageView pointImg;
    private int moveSum = 0;
    protected int topMargin = 15;
    public int moveSpeed = 0;
    protected long uptimeMillis = 5000;
    protected List<ArticleItem> hotDataItems;
    protected String TAG = getClass().getName();
    public boolean hadAdded = false;
    RelativeLayout mScrollerContainer;
    HorsecListener horsecListener;
    MoreListener moreListener;
    ViewFlipper viewFlipper;


    public HorseNightView(Context context) {
        this(context, null);
    }

    @SuppressLint("ClickableViewAccessibility")
    public HorseNightView(Context context, AttributeSet attrs) {
        super(context, attrs);
        View horseNight = LayoutInflater.from(context).inflate(R.layout.home_horse_night_news, null);
        addView(horseNight);
        mScrollerContainer = horseNight.findViewById(R.id.mScrollerContainer);
        viewFlipper = horseNight.findViewById(R.id.viewFlipper);
        // mHorseNightContainer = horseNight.findViewById(R.id.mHorseNightContainer);
        //mHorseNightScroller = horseNight.findViewById(R.id.mHorseNightScroller);
        ass_top_titel = horseNight.findViewById(R.id.ass_top_titel);
        mTop_back = horseNight.findViewById(R.id.mTop_back);
        ass_top_titel_image = horseNight.findViewById(R.id.ass_top_titel_image);
        pointImg = horseNight.findViewById(R.id.img_red_point);
        final int mainColor = AppFactoryGlobalConfig.getAppServerConfigInfo(context).getMainColor();
        mTop_back.setTint(mainColor, mainColor);
        horsecListener = new HorsecListener();
        moreListener = new MoreListener();
        //		mHorseNightContainer=(LinearLayout)LayoutInflater.from(context).inflate(R.layout.horse_night_container, null);
        //		mHorseNightScroller=(HorseNightScroller)LayoutInflater.from(context).inflate(R.layout.horse_night_scroller, null);
        //		mHorseNightScroller.addView(mScrollerContainer);
        //		mScrollerContainer.addView(mHorseNightScroller);
        ass_top_titel.setOnClickListener(moreListener);
        ass_top_titel_image.setOnClickListener(moreListener);
        mTop_back.setOnClickListener(moreListener);
      /*  mHorseNightScroller.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });*/
    }

    public void removeAllData() {
       /* mHandler.views.clear();
        mHorseNightContainer.removeAllViews();
        mHandler.removeMessages(0);
        mHandler.removeMessages(-1);*/

        for (int i = 0; i < viewFlipper.getChildCount(); i++) {
            View child = viewFlipper.getChildAt(i);
            if (child instanceof ViewGroup) {
                ViewGroup chg = ((ViewGroup) child);
                for (int j = 0; j < chg.getChildCount(); j++) {
                    chg.getChildAt(j).setVisibility(View.INVISIBLE);
                }
            }
        }
        viewFlipper.removeAllViews();
        viewFlipper.stopFlipping();
    }


    public void addHorsenightItem(final List<ArticleItem> data,
                                  final ComponentItem componentItem, int title_type) {
        moveSum = 0;
        moreListener.componentItem = componentItem;

        for (int i = 0; i < data.size(); i++) {
            ArticleItem item = data.get(i);
            String newsTitle = item != null ? item.getTitle() : "";


            TextView titleText = new TextView(getContext());
            titleText.setText(newsTitle);
            titleText.setMaxLines(1);
            titleText.setEllipsize(TruncateAt.END);
            titleText.setGravity(Gravity.CENTER_VERTICAL);
            titleText.setTextColor(getResources().getColor(android.R.color.black));
            titleText.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.intime_report_size));
            viewFlipper.addView(titleText);
            titleText.setTag(item);
            titleText.setOnClickListener(v -> {
                if (v.getTag() != null) {
                    JSONObject data1 = (JSONObject) ((ArticleItem) v.getTag()).extendField;
//                        ComponentClickUtils.OpenItemComponent(v.getContext(), componentItem, data);
                    NewsItemClickUtils.OpenItemNewsHandle(getContext(), componentItem.title_type, item,new CatalogItem());
                    TXReportManager.getInstance().app_jhapp_home_subtab_content_interact("关注",
                            componentItem.orginDataObject.optString("title"),
                            "",
                            "",
                            "",
                            "",
                            "",
                            "",
                            item
                    );
                }
            });


        }
        viewFlipper.startFlipping();
    }
    public void addHorsenightItem1(final List<ArticleItem> data, ComponentItem componentItem, int title_type) {
        moreListener.componentItem = componentItem;
        if (title_type == 1) {
            ass_top_titel.setVisibility(View.VISIBLE);
            ass_top_titel.setText(componentItem.getTitle());
            ass_top_titel.setTextColor(DefaultBgUtil.getTintColor(getContext()));
        } else if (title_type == 2) {
            ass_top_titel_image.setVisibility(View.VISIBLE);
            FunKt.load(ass_top_titel_image,componentItem.getTitle());
        }
//        mHandler.removeMessages(0);
        moveSum = 0;
      //  mHorseNightScroller.smoothScrollTo(ScrollView.SCROLLBAR_POSITION_RIGHT, moveSum);
        for (int i = 0; i < data.size(); i++) {

            final LinearLayout itemHorseNightContainer = new LinearLayout(getContext());
            itemHorseNightContainer.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {

                @Override
                public boolean onPreDraw() {
                    moveSpeed = itemHorseNightContainer.getMeasuredHeight();
                    itemHorseNightContainer.getViewTreeObserver().removeOnPreDrawListener(this);
                    return true;
                }
            });

            itemHorseNightContainer.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams itemContainerLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            itemContainerLayoutParams.gravity = Gravity.CENTER;
            itemHorseNightContainer.setPadding(0, topMargin / 2, 0, topMargin / 2);
            itemHorseNightContainer.setLayoutParams(itemContainerLayoutParams);
            TextView titleText = new TextView(getContext());
            titleText.setMaxLines(1);
            titleText.setEllipsize(TruncateAt.END);
            try {
//				titleText.setTypeface(ResourcesCompat.getFont(getContext(),R.font.app_font));
                AppFontToolKt.setTextViewFont(titleText);
            } catch (Exception e) {
            }
            final ArticleItem item = data.get(i);
            horsecListener.componentItem = componentItem;
            LinearLayout.LayoutParams titleTextLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            titleTextLayoutParams.gravity = Gravity.CENTER;
            titleText.setLayoutParams(titleTextLayoutParams);
            titleText.setGravity(Gravity.CENTER_VERTICAL);
            titleTextLayoutParams.leftMargin = 8;
            titleText.setTextColor(getResources().getColor(android.R.color.black));
            titleText.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.intime_report_size));
            String newsType = null;
            String newsTitle = item.getTitle();
            String typeStartMark = getResources().getString(R.string.home_newstype_startmark);
            if (!TextUtils.isEmpty(newsTitle) && newsTitle.startsWith(typeStartMark)) {
                String typeEndMark = getResources().getString(R.string.home_newstype_endmark);
                newsType = newsTitle.substring(0, newsTitle.indexOf(typeEndMark));
                newsType = newsType.replace(typeStartMark, "").replace(typeEndMark, "");
                newsTitle = newsTitle.substring(newsTitle.indexOf(typeEndMark) + 1);
            } else {
                newsType = getResources().getString(R.string.news_report);
            }
            titleText.setText(newsTitle);
            itemHorseNightContainer.addView(titleText);
           // mHorseNightContainer.addView(itemHorseNightContainer);
            itemHorseNightContainer.setOnClickListener(horsecListener);
            itemHorseNightContainer.setTag(i);
        }
//        mHorseNightContainer.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
//
//            @Override
//            public boolean onPreDraw() {
//                getViewTreeObserver().removeOnPreDrawListener(this);
//                mContainerMesureWidh = mHorseNightContainer.getMeasuredWidth();
//                mContainerMesurHeight = mHorseNightContainer.getMeasuredHeight() * 2;
//                mContainerLookWidth = mHorseNightScroller.getMeasuredHeight();
//                //				moveSum+=moveSpeed;
//                //第一次加载后设置一次红点的显示与否,只有租户id为皇中才设置 b38d4ffb2cc923818dda517360531833
//                if ("b38d4ffb2cc923818dda517360531833".equals(getResources().getString(R.string.tenantid))){
//                    if (data.size() != 0) {
//                        SharedPreferencesCache sharedPreferencesCache = new SharedPreferencesCache(getContext());
//                        boolean isRead = sharedPreferencesCache.getBoolean(data.get(0).getId() + "");
//                        if (isRead) {
//                            pointImg.setVisibility(View.GONE);
//                        } else {
//                            pointImg.setVisibility(View.VISIBLE);
//                        }
//                    }
//                }
//
//
//                if (data.size() > 1)//����һ���Ź���
//                    mHandler.sendEmptyMessageDelayed(0, uptimeMillis);
//                return true;
//            }
//        });
    }


    protected class ScrollHandle extends Handler {
        protected boolean flag = false;
        List<View> views = new ArrayList<View>();

        int dip2px(float dpValue) {
            final float scale = getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            if (msg.what == -1) {
//                if (mHorseNightContainer.getChildCount() > 1) {
//                    View view = mHorseNightContainer.getChildAt(0);
//                    mHorseNightContainer.removeView(view);
//
//                    for (int i = 0; i < mHorseNightContainer.getChildCount(); i++) {
//                        views.add(mHorseNightContainer.getChildAt(i));
//
//                    }
//                    views.add(view);
//                    mHorseNightContainer.removeAllViews();
//                    mHorseNightScroller.computeScroll();
//                    mHorseNightScroller.smoothScrollTo(ScrollView.SCROLLBAR_POSITION_RIGHT, 0);
//                    for (View item : views) {
//                        mHorseNightContainer.addView(item);
//                    }
//                    views.clear();
//                }
//                return;
//            }
//            mHorseNightScroller.smoothScrollTo(ScrollView.SCROLLBAR_POSITION_RIGHT, moveSpeed);
            sendEmptyMessageDelayed(-1, 255);
//            mHandler.sendEmptyMessageDelayed(0, uptimeMillis);
            //说是只有需要这个功能 b38d4ffb2cc923818dda517360531833
//            if ("b38d4ffb2cc923818dda517360531833".equals(getResources().getString(R.string.tenantid))){
//                //在调换位置之后处理一次点的显示，由于做了头部数据变成尾部的处理，所以改变一下index的值
//                View selectView = mHorseNightContainer.getChildAt(0);
//                int index = (int) selectView.getTag();
//                if (index != hotDataItems.size() - 1) {
//                    index = index + 1;
//                } else {
//                    index = 0;
//                }
//
//                ArticleItem articleItem = hotDataItems.get(index);
////            Log.e("位置", index + "," + articleItem.getTitle());
//                SharedPreferencesCache sharedPreferencesCache = new SharedPreferencesCache(getContext());
//                boolean isRead = sharedPreferencesCache.getBoolean(articleItem.getId() + "");
//                if (isRead) {
//                    pointImg.setVisibility(View.GONE);
//                } else {
//                    pointImg.setVisibility(View.VISIBLE);
//                }
//            }

        }
    }

    public void refreshData1(List<ArticleItem> data, ComponentItem componentItem, int title_type) {
        if (data != null && data.size() > 0) {
            hotDataItems = data;
            try {
                hadAdded = true;
            } catch (Exception e) {
            }
            removeAllData();
            addHorsenightItem(hotDataItems, componentItem, title_type);
        } else if (hotDataItems != null && hotDataItems.size() > 0) {
            try {
                hadAdded = true;
            } catch (Exception e) {
            }
            removeAllData();
            addHorsenightItem(hotDataItems, componentItem, title_type);
        } else {
            try {
                hadAdded = false;
            } catch (Exception e) {
            }
        }
    }

    public void refreshData(List<ArticleItem> data,
                            ComponentItem componentItem, int title_type) {
        moreListener.componentItem = componentItem;
        if (title_type == 1) {
            ass_top_titel.setVisibility(View.VISIBLE);
            ass_top_titel.setText(componentItem.getTitle());
            JSONObject other_field = componentItem.orginDataObject.optJSONObject("other_field");
            if (other_field != null) {
                int title_color_type = other_field.optInt("title_color_type");
                if (title_color_type == 1){
                    String title_color = other_field.optString("title_color", "#FF000000");
                    try {
                        ass_top_titel.setTextColor(Color.parseColor(title_color));
                    } catch (Exception e) {
                        e.printStackTrace();
                        ass_top_titel.setTextColor(DefaultBgUtil.getTintColor(getContext()));
                    }
                }else{
                    ass_top_titel.setTextColor(DefaultBgUtil.getTintColor(getContext()));
                }

            } else {

                ass_top_titel.setTextColor(DefaultBgUtil.getTintColor(getContext()));
            }
        } else if (title_type == 2) {
            ass_top_titel_image.setVisibility(View.VISIBLE);
            FunKt.load(ass_top_titel_image,componentItem.getTitle());
        }

        if (data != null && data.size() > 0) {
            hotDataItems = data;
            try {
                hadAdded = true;
            } catch (Exception e) {
            }
            removeAllData();
            addHorsenightItem(hotDataItems, componentItem, title_type);
        } else if (hotDataItems != null && hotDataItems.size() > 0) {
            try {
                hadAdded = true;
            } catch (Exception e) {
            }
            removeAllData();
            addHorsenightItem(hotDataItems, componentItem, title_type);
        } else {
            try {
                hadAdded = false;
            } catch (Exception e) {
            }
        }


        class HorsecListener implements OnClickListener {
            ComponentItem componentItem;

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                int index = (int) v.getTag();
                JSONObject data = hotDataItems.get(index).orginDataObject;
                ComponentClickUtils.OpenItemComponent(getContext(), componentItem,
                        data);
            }

        }

        class HorsecListener1 implements OnClickListener {
            ComponentItem componentItem;
            JSONObject data;

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (componentItem != null) {
                    int index = (int) v.getTag();
                    data = hotDataItems.get(index).orginDataObject;
                    ComponentClickUtils.OpenItemComponent(getContext(),
                            componentItem, data);
                }
            }

        }

    }


    class HorsecListener implements OnClickListener {
        ComponentItem componentItem;

        @Override
        public void onClick(View v) {
            int index = (int) v.getTag();
            JSONObject data = hotDataItems.get(index).orginDataObject;
//            SharedPreferencesCache sharedPreferencesCache = new SharedPreferencesCache(getContext());
//            sharedPreferencesCache.cacheBoolean(hotDataItems.get(index).getId() + "", true);
            pointImg.setVisibility(View.GONE);
            ComponentClickUtils.OpenItemComponent(v.getContext(), componentItem, data);
        }

    }

    class MoreListener implements View.OnClickListener {
        ComponentItem componentItem;

        @Override
        public void onClick(View v) {
            if (componentItem != null) {
                ComponentClickUtils.OpenItemComponent(getContext(), componentItem,
                        null);
            }

        }

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (viewFlipper != null)
            viewFlipper.stopFlipping();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (viewFlipper != null && viewFlipper.getChildCount() > 0)
            viewFlipper.startFlipping();
    }
}